<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">号码库后台管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="手机号"
          :clearable="clearable">
          <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="login-code">
          <div style="  color: #707070;" @click="getSmsCode">
            {{ isCounting ? `重新获取(${countdown}s)` : '获取验证码' }}
          </div>
        </div>
      </el-form-item>

      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 All Rights Reserved.</span>
    </div>

    <el-dialog title="请选择管理员授权本次登录!" :visible.sync="leaderFormVisible" width="400px">
      <el-form ref="leaderForm" :model="leaderForm" :rules="leaderRules">
        <el-form-item prop="username">
          <el-select v-model="leaderForm.username" placeholder="请选择">
            <el-option v-for="item in leaderList" :key="item.id" :label="item.name"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item prop="code">
          <el-input
            v-model="leaderForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
          </el-input>
          <div class="login-code">
            <div style="  color: #707070;" @click="getSmsCode2">
              {{ isCounting2 ? `重新获取(${countdown2}s)` : '获取验证码' }}
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="leaderFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="leaderFormSubmit('leaderForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getCodeImg, getSmsCode, getSmsCode2, prepareLeaderLogin, prepareLogin} from "@/api/login";
import Cookies from "js-cookie";
import {decrypt, encrypt} from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      leaderList: [],
      clearable: true,
      leaderFormVisible: false,
      codeUrl: "",
      countdown: 0, // 倒计时秒数
      countdown2: 0,
      isCounting: false, // 是否正在倒计时
      isCounting2: false, // 是否正在倒计时
      leaderForm: {
        username: "",
        code: "",
      },
      leaderRules: {
        username: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },

    getSmsCode() {
      // 获取用户名
      const username = this.loginForm.username;
      // 定义手机号正则表达式
      const phoneRegex = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      // 校验手机号格式
      if (phoneRegex.test(username)) {
        console.log("手机号格式正确");
        if (this.isCounting) {
          return;
        }
        // 设置倒计时
        this.countdown = 60; // 60秒倒计时
        this.isCounting = true;

        // 启动倒计时
        const timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            clearInterval(timer); // 停止倒计时
            this.isCounting = false; // 恢复按钮状态
          }
        }, 1000);

        getSmsCode(this.loginForm).then(res => {
          this.$modal.msgSuccess("短信已成功发送你手机,请注意查收!");
        }).catch(() => {
          // 如果发送失败，停止倒计时
          clearInterval(timer);
          this.isCounting = false;
        })
      } else {
        this.$modal.msg("请先输入手机号!");
      }
    },
    getSmsCode2() {
      // 获取用户名
      const username = this.leaderForm.username;
      // 定义手机号正则表达式
      const phoneRegex = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      // 校验手机号格式
      if (phoneRegex.test(username)) {
        console.log("手机号格式正确");
        if (this.isCounting2) {
          return;
        }
        // 设置倒计时
        this.countdown2 = 60; // 60秒倒计时
        this.isCounting2 = true;
        // 启动倒计时
        const timer = setInterval(() => {
          this.countdown2--;
          if (this.countdown2 <= 0) {
            clearInterval(timer); // 停止倒计时
            this.isCounting2 = false; // 恢复按钮状态
          }
        }, 1000);

        const queryData = {
          ...this.loginForm,
          leaderUserName: this.leaderForm.username
        }
        getSmsCode2(queryData).then(res => {
          this.$modal.msgSuccess("短信已成功发送你手机,请注意查收!");
        }).catch(() => {
          // 如果发送失败，停止倒计时
          clearInterval(timer);
          this.isCounting2 = false;
        })
      } else {
        this.$modal.msg("请先输入手机号!");
      }
    },

    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    //需要领导进一步登录验证
    async leaderFormSubmit(formName) {
      const valid = await this.$refs[formName].validate();
      if (!valid) {
        return false;
      }

      prepareLeaderLogin(this.leaderForm).then(res => {
        if (res.code == 200) {
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      })
    },

    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30});
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          //这里先调一个本人的接口获取是否需要再次领导验证码页面,如果需要,领导的验证码和后端对比上后返回true在走下面
          prepareLogin(this.loginForm).then(res => {
            if (res.data.tag != 200) {
              this.leaderList = [];
              if (res.data.tag == 105) {
                this.leaderList = [{'name': '李雪-15523232999', 'value': '15523232999'},
                  {'name': '李洪-13251325888', 'value': '13251325888'}];
              } else if (res.data.tag == 106) {
                // this.leaderList = [
                //   {'name': '谢欢-18523237788', 'value': '18523237788'},
                //   {'name': '周亨莉-18580800101', 'value': '18580800101'},
                //   {'name': '洪朝晨-18580199991', 'value': '18580199991'},];
                this.$modal.msgError("请在直播基地专线房间登录!")
                return;
              } else if (res.data.tag == 107) {
                this.leaderList = [{'name': '邓玲-13002310010', 'value': '13002310010'},
                  {'name': '胡权-16602377777', 'value': '16602377777'}];
              } else if (res.data.tag == 109) {
                this.leaderList = [{'name': '樊春燕-15523322332', 'value': '15523322332'},
                  {'name': '周健-18696855888', 'value': '18696855888'}];
              }
              this.leaderFormVisible = true;
            } else {
              this.$store.dispatch("Login", this.loginForm).then(() => {
                this.$router.push({path: this.redirect || "/"}).catch(() => {
                });
              }).catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {
                  this.getCode();
                }
              });
            }
          })
        }
      });
    }
  }
}
;
</script>

<style rel="stylesheet/scss" lang="scss">

.login-code .el-button {
  padding: 0;
  font-size: 14px;
  color: #707070;
}

.login-code .el-button:disabled {
  color: #c0c4cc; /* 禁用时的颜色 */
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
